package com.yin.waimai.service;

import com.yin.waimai.dto.OrderDTO;
import com.yin.waimai.dto.OrderNotificationDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Service
public class WebSocketService {

    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    public WebSocketService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    // 向所有配送员广播新订单
    public void broadcastNewOrder(OrderDTO order) {
        OrderNotificationDTO notification = new OrderNotificationDTO();
        notification.setOrderNumber(order.getOrderNumber());
        notification.setItemDescription(order.getItemDescription());
        notification.setWeight(order.getWeight());
        notification.setCalculatedFee(order.getCalculatedFee()); // 直接使用BigDecimal类型
        notification.setShipperInfo(order.getShipperInfo());
        notification.setRecipientInfo(order.getRecipientInfo());
        notification.setCreationTime(order.getCreationTime().toString());
        notification.setStatus(order.getStatus().toString());
        notification.setMessage("新订单等待接单");
        notification.setType("NEW_ORDER");
        
        messagingTemplate.convertAndSend("/topic/orders/new", notification);
    }

    // 通知订单已被接单
    public void notifyOrderAccepted(OrderDTO order, String deliveryPersonName) {
        OrderNotificationDTO notification = new OrderNotificationDTO();
        notification.setOrderNumber(order.getOrderNumber());
        notification.setMessage("订单已被配送员 " + deliveryPersonName + " 接单");
        notification.setType("ORDER_ACCEPTED");
        
        messagingTemplate.convertAndSend("/topic/orders/" + order.getOrderNumber(), notification);
    }
    
    // 通知订单已被管理员分配
    public void notifyOrderAssigned(OrderDTO order, String deliveryPersonName) {
        OrderNotificationDTO notification = new OrderNotificationDTO();
        notification.setOrderNumber(order.getOrderNumber());
        notification.setMessage("订单已被管理员分配给配送员 " + deliveryPersonName);
        notification.setType("ORDER_ASSIGNED");
        
        messagingTemplate.convertAndSend("/topic/orders/" + order.getOrderNumber(), notification);
    }
}